#!/bin/bash

# 洗护系统生产环境启动脚本

set -e

echo "🚀 启动洗护系统生产环境..."

# 检查Docker和Docker Compose
check_docker() {
    if ! command -v docker &> /dev/null; then
        echo "❌ Docker未安装，请先安装Docker"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        echo "❌ Docker Compose未安装，请先安装Docker Compose"
        exit 1
    fi
    
    echo "✅ Docker环境检查通过"
}

# 创建必要的目录
create_directories() {
    echo "📁 创建必要的目录..."
    mkdir -p uploads logs mysql/data mysql/conf.d nginx/conf.d
    
    # 设置权限
    chmod 755 uploads logs
    
    echo "✅ 目录创建完成"
}

# 检查配置文件
check_config() {
    echo "🔧 检查配置文件..."
    
    if [ ! -f "docker-compose.yml" ]; then
        echo "❌ docker-compose.yml文件不存在"
        exit 1
    fi
    
    if [ ! -f "scripts/mysql-setup.sql" ]; then
        echo "❌ MySQL初始化脚本不存在"
        exit 1
    fi
    
    echo "✅ 配置文件检查通过"
}

# 构建镜像
build_images() {
    echo "🔨 构建Docker镜像..."
    docker-compose build --no-cache
    echo "✅ 镜像构建完成"
}

# 启动服务
start_services() {
    echo "🚀 启动服务..."
    
    # 先启动数据库和Redis
    echo "启动数据库和Redis..."
    docker-compose up -d mysql redis
    
    # 等待数据库启动
    echo "等待数据库启动..."
    sleep 30
    
    # 启动后端应用
    echo "启动后端应用..."
    docker-compose up -d backend
    
    # 等待后端启动
    echo "等待后端应用启动..."
    sleep 20
    
    # 启动Nginx
    echo "启动Nginx..."
    docker-compose up -d nginx
    
    echo "✅ 所有服务启动完成"
}

# 健康检查
health_check() {
    echo "🔍 执行健康检查..."
    
    if [ -f "scripts/health-check.sh" ]; then
        chmod +x scripts/health-check.sh
        ./scripts/health-check.sh
    else
        echo "⚠️ 健康检查脚本不存在，跳过自动检查"
        echo "请手动访问 http://localhost:8080/api/test/db-info 检查服务状态"
    fi
}

# 显示服务状态
show_status() {
    echo "📊 服务状态:"
    docker-compose ps
    
    echo ""
    echo "🌐 访问地址:"
    echo "  - 后端API: http://localhost:8080"
    echo "  - 数据库控制台: http://localhost:8080/db/console"
    echo "  - 前端应用: http://localhost (如果配置了Nginx)"
    
    echo ""
    echo "🔧 管理命令:"
    echo "  - 查看日志: docker-compose logs -f [service_name]"
    echo "  - 重启服务: docker-compose restart [service_name]"
    echo "  - 停止服务: docker-compose down"
    echo "  - 查看状态: docker-compose ps"
}

# 主函数
main() {
    echo "🎯 洗护系统生产环境启动"
    echo "========================================"
    
    check_docker
    create_directories
    check_config
    build_images
    start_services
    health_check
    show_status
    
    echo "========================================"
    echo "🎉 洗护系统启动完成！"
    echo "📍 系统已在生产模式下运行"
}

# 错误处理
trap 'echo "❌ 启动过程中发生错误，正在清理..."; docker-compose down; exit 1' ERR

# 执行主函数
main "$@"
